package com.pdstudio.weather;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.pdstudio.apapter.WaterStationAdapter;
import com.pdstudio.app.Application;
import com.pdstudio.app.Application.EventHandler;
import com.pdstudio.bean.WaterRiver;
import com.pdstudio.bean.WaterStation;
import com.pdstudio.charts.HydrologicalStationActivity;
import com.pdstudio.http.StationHttpMethod;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.view.ViewHolder;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class WaterActivity extends Activity implements EventHandler {

	private WaterStationAdapter waterBaseAdapter;
	private ListView lvWater;
	private List<WaterStation> waterStations;
	private Handler handler = null;

	private Spinner spinner;
	private List<WaterRiver> waterRivers;
	private ArrayAdapter riversArrayAdapter;
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;
	
	private String[] mRivers=null; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_water);

		Application.mListeners.add(this);
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		lvWater = (ListView) findViewById(R.id.waterlist);
		spinner = (Spinner) findViewById(R.id.Spinner01);
		spinner.setPrompt("选择河道");
		newRunnable();

	}

	private void newRunnable() {
		// TODO Auto-generated method stub

		// 开一条子线程加载网络数据
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(0);
					Message msg;
					StationHttpMethod http = new StationHttpMethod(
							WaterActivity.this);
					waterRivers = http.GetRivers(mSpUtil.getAuthCode(),
							mApplication.getCurSimpleCity().cityCode);
					msg = handler.obtainMessage(1, waterRivers);
					handler.sendMessage(msg);

					waterStations = http.GetWaterStationsByRiverId(
							mSpUtil.getAuthCode(),
							waterRivers.get(0).getRiverName());
					msg = handler.obtainMessage(0, waterStations);
					handler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};

		try {
			// 开启线程
			new Thread(runnable).start();
			// handler与线程之间的通信及数据处理
			handler = new Handler() {
				public void handleMessage(Message msg) {
					if (msg.what == 1) {
						// Toast.makeText(getApplicationContext(), "加载数据中", 0)
						// .show();
						// msg.obj是获取handler发送信息传来的数据
						@SuppressWarnings("unchecked")
						List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

						if (msg != null && msg.obj != null) {
							waterRivers = (List<WaterRiver>) msg.obj;

//							for (WaterRiver o : waterRivers) {
//								Map<String, Object> map = new HashMap<String, Object>();
//								map.put("riverName", o.getRiverName());								
//								list.add(map);
//							}
							mRivers=new String[waterRivers.size()];
							for(int i = 0;i<waterRivers.size();i++){								
								mRivers[i]=((WaterRiver)waterRivers.get(i)).getRiverName();
							}
						}
						// 绑定数据
						setWaterRivers(list);
					}
					if (msg.what == 0) {
						Toast.makeText(getApplicationContext(), "加载数据中", 0)
								.show();
						// 给ListView绑定数据
						setWaterStations(waterStations);
					}
				}

			};
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.water, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void setWaterStations(List<WaterStation> stations) {
		try {
			waterBaseAdapter = new WaterStationAdapter(this, stations);
			lvWater.setAdapter(waterBaseAdapter);
			lvWater.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> v, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					try {
						Intent intent = new Intent(WaterActivity.this,
								HydrologicalStationActivity.class);
						Bundle b = new Bundle();
						b.putString(
								"staioninfo",
								((ViewHolder) view.getTag()).trendImg.getTag() == null ? "0"
										: ((ViewHolder) view.getTag()).trendImg
												.getTag().toString());
						intent.putExtras(b);
						startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			});
		} catch (Exception e) {
		}
	}

	private void setWaterRivers(List<Map<String, Object>> waterRivers) {
		
		riversArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mRivers);         
        //设置下拉列表的风格  
		riversArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);          
        //将adapter 添加到spinner中  
        spinner.setAdapter(riversArrayAdapter);  
          
        //添加事件Spinner事件监听    
        spinner.setOnItemSelectedListener(new SpinnerSelectedListener());  
          
        //设置默认值  
        spinner.setVisibility(View.VISIBLE);  

	}
	
	//使用数组形式操作  
    class SpinnerSelectedListener implements OnItemSelectedListener{  
  
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,  
                long arg3) {  
        	
        	try {
    			Thread thread = new Thread() {
    				@Override
    				public void run() {
    					StationHttpMethod http = new StationHttpMethod(
    							WaterActivity.this);
    					waterStations = http.GetWaterStationsByRiverId(
    							mSpUtil.getAuthCode(),
    							spinner.getSelectedItem().toString());
    					Message msg = handler.obtainMessage(0, waterStations);
    					handler.sendMessage(msg);
    				}
    			};
    			thread.start();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
        }  
  
        public void onNothingSelected(AdapterView<?> arg0) {  
        }  
    }  

	@Override
	public void onCityComplite() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNetChange() {
		// TODO Auto-generated method stub

	}
}
